﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Jc.MicroDesigner.Objects;
using Jc.MicroDesigner.Management;
using System.Reflection;
using System.Drawing;

namespace Jc.MicroDesigner.Drawings.Tools
{
    /// <summary>
    /// Инструмент для любых элементов схемы
    /// </summary>
    public class CircuitElementTool : DrawingTool
    {
        private Type _ToolType = null;

        /// <summary>
        /// Создать инструмент на основе типа
        /// </summary>
        /// <param name="t">Тип инструмента</param>
        /// <param name="name">имя</param>
        public CircuitElementTool(Type tooltype, string name) : this(tooltype, name, "")
        {

        }

        /// <summary>
        /// Создать инструмент на основе типа
        /// </summary>
        /// <param name="t">Тип инструмента</param>
        /// <param name="name">имя</param>
        /// <param name="category">Категория</param>
        public CircuitElementTool(Type tooltype, string name, string category)
        {
            _Name = name;
            _Category = category;
            _ToolType = tooltype;
            this._ToolCursor = Cursors.Cross;
            if ((_ToolType == null) || !_ToolType.IsSubclassOf(typeof(CircuitElement)))
            {
                throw new Exception("Неверный тип инструмента, тип должен наследовать CircuitElement");
            }
        }

        public override void OnMouseDown(DrawPanel panel, MouseEventArgs e)
        {
            if ((panel.ObjManager != null) && (panel.ObjManager != null))
            {
                ConstructorInfo cinfo = _ToolType.GetConstructor(new Type[] { typeof(ObjectManager) });
                CircuitElement element = (CircuitElement)cinfo.Invoke(new object[] { panel.ObjManager });
                if (panel.Discreteness > 0)
                {
                    Point d = panel.GetDiscreetCoord(e.Location);
                    element.DrawOptions.Top = d.Y;
                    element.DrawOptions.Left = d.X;
                }
                else
                {
                    element.DrawOptions.Left = e.X;
                    element.DrawOptions.Top = e.Y;
                }
                element.Name = panel.ObjManager.NewElementName(_ToolType);
                panel.ObjManager.Elements.Add(element);
                panel.Invalidate();
            }
        }
    }
}